<template>
    <div class="table-page">
        <div class="table-search-box" @keyup.enter="search">
            <div class="search-item">
                <label>科目：</label>
                <!--                <el-cascader
                                    v-model="queryData.classificationId"
                                    :options="classificationInfo"
                                    :show-all-levels="false"
                                    filterable
                                    clearable
                                    :props="{
                                        value: 'id',
                                        label: 'name',
                                        emitPath: false,
                                        checkStrictly: true
                                    }"

                                ></el-cascader>-->
                <category-select
                    :category-id.sync="queryData.categoryId"
                    :props="{}"
                />
            </div>
            <div class="search-item">
                <label>章节名称：</label>
                <div class="table-query-input">
                    <el-input
                        v-model="queryData.name"
                        clearable
                        placeholder="章节名称"
                    ></el-input>
                </div>
            </div>
            <div class="search-item">
                <el-button
                    type="primary"
                    icon="el-icon-search"
                    :loading="tableLoading"
                    @click="clickSearch()"
                >搜索
                </el-button>
            </div>
            <div class="search-item">
                <el-button
                    icon="el-icon-refresh"
                    :loading="tableLoading"
                    @click="resetSearch()"
                >重置
                </el-button>
            </div>
        </div>
        <div class="table-operation-box">
            <el-button
                type="primary"
                icon="el-icon-plus"
                style="margin-bottom: 2em"
                @click="clickAdd('添加章节', openExamChaptersAdd)"
            >添加一级章节
            </el-button>
            <el-button
                type="primary"
                style="margin-bottom: 2em"
                icon="el-icon-folder"
                @click="importChapter"
            >导入
            </el-button>
        </div>
        <div class="table-data-box">
            <el-table
                ref="table"
                v-loading="tableLoading"
                :data="tableData"
                border
                style="width: 100%;min-height:40em"
                row-key="id"
                lazy
                :load="load"
                :tree-props="{
                    children: 'children',
                    hasChildren: 'hasChildren'
                }"
            >
                <el-table-column
                    prop="classificationName"
                    label="科目"
                    min-width="180"
                >
                </el-table-column>
                <el-table-column prop="name" label="章节名称" min-width="180">
                </el-table-column>
                <el-table-column
                    prop="remark"
                    label="备注"
                    min-width="180"
                ></el-table-column>
                <el-table-column
                    prop="sort"
                    label="排序"
                    min-width="180"
                ></el-table-column>
                <el-table-column
                    prop="createdTime"
                    label="创建时间"
                    width="160"
                ></el-table-column>
                <el-table-column
                    prop="createdByName"
                    label="最后操作者"
                    width="160"
                ></el-table-column>
                <el-table-column label="操作" min-width="400" align="center">
                    <template slot-scope="scope">
                        <el-button
                            v-if="!scope.row.edit"
                            class="primary"
                            type="text"
                            size="mini"
                            icon="el-icon-edit"
                            :loading="scope.row.opLoading"
                            @click="
                                clickSimpleEdit(
                                    scope.row,
                                    '章节编辑',
                                    change(scope.row)
                                )
                            "
                        >编辑
                        </el-button>
                        <el-button
                            v-if="!scope.row.edit"
                            class="danger"
                            type="text"
                            icon="el-icon-delete"
                            size="mini"
                            :loading="scope.row.opLoading"
                            @click="
                                tableDelete(
                                    '/exam/chapters/delete',
                                    {
                                        id: scope.row.id
                                    },
                                    true,
                                    refresh()
                                )
                            "
                        >删除
                        </el-button>
                        <el-button
                            v-if="!scope.row.edit"
                            class="primary"
                            type="text"
                            size="mini"
                            icon="el-icon-plus"
                            :loading="scope.row.opLoading"
                            @click="
                                addChild(scope.$index, scope.row, '添加子章节')
                            "
                        >添加子级
                        </el-button>
                        <el-button
                            v-if="!scope.row.edit"
                            class="primary"
                            type="text"
                            size="mini"
                            icon="el-icon-document"
                            :loading="scope.row.opLoading"
                            @click="toPracticeQuestionPage(scope.row)"
                        >章节练习
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <div v-if="pageData.total" class="xy-between table-page-box">
            <el-pagination
                :current-page.sync="pageData.currentPage"
                :page-sizes="pageData.pageSizes"
                :page-size.sync="pageData.pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="pageData.total"
            >
            </el-pagination>
        </div>
        <el-dialog
            :title="dialogFormTitle"
            :visible.sync="dialogFormVisible"
            width="50%"
        >
            <el-form
                ref="dataForm"
                :model="dataForm"
                label-width="8em"
                :rules="dataFormRule"
                class="table-edit-from"
            >
                <el-form-item label="章节名称" prop="name">
                    <el-input v-model="dataForm.name"></el-input>
                </el-form-item>
                <!--                <el-form-item label="所属学科" prop="classificationName" v-if="!addFirst">-->
                <!--                    <el-input-->
                <!--                        v-model="dataForm.classificationName"-->
                <!--                        :disabled="!addFirst"-->
                <!--                    ></el-input>-->
                <!--                </el-form-item>-->
                <el-form-item
                    v-show="addFirst"
                    label="科目"
                    prop="classificationId"
                >
                    <el-cascader
                        :key="key"
                        v-model="dataForm.classificationId"
                        :props="classificationProps"
                        :show-all-levels="false"
                        filterable
                        clearable
                    ></el-cascader>
                </el-form-item>
                <el-form-item
                    v-show="!addFirst"
                    label="科目"
                    prop="classificationName"
                >
                    <el-input
                        v-model="dataForm.classificationName"
                        disabled
                    ></el-input>
                </el-form-item>
                <!--                <el-form-item label="上级节点" prop="parentId" v-if="!dataForm.addAction">-->
                <!--                    <template >-->
                <!--                        <div>-->
                <!--                            <el-cascader-->
                <!--                                v-model="dataForm.parentId"-->
                <!--                                :options="rowData"-->
                <!--                                placeholder="上级节点"-->
                <!--                                :show-all-levels="false"-->
                <!--                                clearable-->
                <!--                                filterable-->
                <!--                                :props="{-->
                <!--                                    value: 'id',-->
                <!--                                    label: 'name',-->
                <!--                                    emitPath: false,-->
                <!--                                    disabled: 'edit',-->
                <!--                                    checkStrictly: true-->
                <!--                                }"-->
                <!--                                @change="-->
                <!--                                    vl =>-->
                <!--                                        selectParent(-->
                <!--                                            vl,-->
                <!--                                            dataForm,-->
                <!--                                            dataForm.parent ||-->
                <!--                                                tableData-->
                <!--                                        )-->
                <!--                                "-->
                <!--                            >-->
                <!--                            </el-cascader>-->
                <!--                        </div>-->
                <!--                    </template>-->
                <!--                </el-form-item>-->
                <el-form-item label="备注" prop="remark">
                    <el-input v-model="dataForm.remark"></el-input>
                </el-form-item>
                <el-form-item label="排序" prop="sort">
                    <el-input v-model.number="dataForm.sort"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button :loading="submitFlag" @click="dialogClose"
                >取 消</el-button
                >
                <el-button :loading="submitFlag" type="primary" @click="save"
                >保 存</el-button
                >
            </span>
        </el-dialog>
    </div>
</template>

<script>
import { TablePage } from "@/layout/mixin/iVue.js";
import { mapState } from "vuex";
import { treeList2Tree, beanCopy } from "@/utils/index.js";
import {
    fetchClassificationChildren,
    fetchClassificationFirst,
    fetchClassificationList2
} from "@/api/course";
import { getLazyChildren } from "@/api/exam";
import CategorySelect from "@/components/CategorySelect";

export default {
    name: "ExamChapters",
    components: {CategorySelect},
    mixins: [TablePage],
    data() {
        return {
            maps: new Map(),
            queryData: {
                categoryId: ""
            },
            classficationQueryData: {
                size: 1000
            },
            ppId: null,
            rowData: {},
            key: 0,
            classificationProps: {
                lazy: true,
                checkStrictly: true,
                emitPath: false,
                lazyLoad: this.getClassification
            },
            initAddForm: {
                id: null,
                name: null,
                remark: null,
                parentId: null
            },
            addFirst: false,
            initList: [],
            classificationInfo: [],
            dataFormRule: {
                name: [
                    { required: true, message: "请输入章节名", trigger: "blur" }
                ],
                classificationId: [
                    { required: true, message: "请选择科目", trigger: "blur" }
                ],
                sort: [
                    { required: true, message: "排序不能为空" },
                    { type: "number", message: "排序必须为数字值" }
                ]
            }
        };
    },
    computed: {
        ...mapState({})
    },
    mounted() {},

    created() {
        //this.getClassfication();
    },
    methods: {
        refresh() {
            this.tableData = [];
            this.search();
        },
        clearQuery() {
            (this.queryData = {}), this.search();
        },
        search(queryData) {
            this.loadTable("/exam/chapters/getLazyPage", queryData, true);
        },
        //获取课程所属科目
        getClassfication() {
            fetchClassificationList2(this.classficationQueryData).then(res => {
                this.classificationInfo = treeList2Tree(res);
            });
        },
        openExamChaptersAdd() {
            this.dataForm.addAction = true;
            this.addFirst = true;
        },

        addChild(index, row, dialogFormTitle) {
            this.dataForm.classificationId = row.classificationId;
            this.dataForm.classificationName = row.classificationName;
            this.dataForm.parentId = row.id;
            this.dataForm.addAction = true;
            this.ppId = row.parentId;
            this.addFirst = false;
            this.dialogFormVisible = true;
            this.dialogFormTitle = dialogFormTitle;
        },
        change(data) {
            this.rowData = data;
            this.addFirst = false;
        },
        toPracticeQuestionPage(data) {
            this.$router.push({
                name: "ExamPracticeQuestion",
                params: {
                    id: data.id,
                    paperType: "chapterpractice",
                    classificationId: data.classificationId
                }
            });
        },
        save() {
            this.formDataSave("/exam/chapters/update").then(res => {
                this.refresh();
            });
        },
        reLoad(pid, ppid, type) {
            const { tree, treeNode, resolve } = this.maps.get(pid);
            if (!tree) {
                const { tree, treeNode, resolve } = this.maps.get(ppid);
                this.$set(
                    this.$refs.table.store.states.lazyTreeNodeMap,
                    ppid,
                    []
                );
            } else {
                this.$set(
                    this.$refs.table.store.states.lazyTreeNodeMap,
                    pid,
                    []
                );
            }
            if (tree) {
                this.load(tree, treeNode, resolve);
            }
        },
        importChapter() {
            this.$router.push({ name: "ImportExamChapter" });
        },
        getClassification(node, resolve) {
            const { level } = node;
            let disable = false;
            if (!node.data) {
                fetchClassificationFirst().then(res => {
                    if (res !== null) {
                        const nodes = Array.from(res).map(item => {
                            disable =
                                this.currentClassificationId !== null &&
                                item.id === this.currentClassificationId;
                            return {
                                value: item.id,
                                label: `${item.name}`,
                                leaf:
                                    level >= (item.children.length > 0 ? 1 : 0),
                                disabled: disable
                            };
                        });
                        resolve(nodes);
                    }
                });
            } else {
                fetchClassificationChildren({ id: node.data.value }).then(
                    res => {
                        const nodes = Array.from(res).map(item => {
                            disable =
                                (this.currentClassificationId !== null &&
                                    item.id === this.currentClassificationId) ||
                                this.currentClassificationId === item.parentId;
                            return {
                                value: item.id,
                                label: `${item.name}`,
                                leaf:
                                    level >=
                                    (item.children.length > 0 ? level + 1 : 0),
                                disabled: disable
                            };
                        });
                        resolve(nodes);
                    }
                );
            }
        },
        load(tree, treeNode, resolve) {
            this.maps.set(tree.id, { tree, treeNode, resolve });
            setTimeout(() => {
                getLazyChildren({ id: tree.id }).then(res => {
                    resolve(res);
                });
            }, 1000);
        }
    }
};
</script>

<style lang="scss" scoped></style>
